import axios from 'axios'
import state from '../store/store';
function ajax(url, data, method = 'get', callBack) {
    axios({
        method: method,
        url: 'https://www.meiguotec.com/house-beta/api/'+url,
        data: data,
        headers: {
            "Authorization": state.state.token,
        }
    }).then(response => {
        callBack(response);
    }).catch(error => {
        callBack(error)
    })
}
function login() {
    // return
    state.state.userId = decodeURIComponent(GetQueryString('userId'))
    state.state.token = GetQueryString('token')
    // state.state.weixinNickname = decodeURIComponent(GetQueryString('weixinNickname'))
    // state.state.weixinPortrait = decodeURIComponent(GetQueryString('weixinPortrait'))
    console.log(1111,state.state.token)
    if(state.state.token!=''){
        return
    }
    // if(state.state.token !='' && state.state.userId !=''){
    //     return 
    // }
    var bodyParameter = {
        appid:state.state.appid,
        source:'微信公众号',
        afterLoginUrl: window.location.href
    };
    var api = "weixin/state";
    ajax(api,bodyParameter, "post", ret => {
        if (ret) {
            if (ret.data.code == 200) {
            console.log(ret)
                console.log(window.location.href)
                var url =
                    "https://open.weixin.qq.com/connect/oauth2/authorize?" +
                    "appid=" +
                    ret.data.appid +
                    "&redirect_uri=" +
                    decodeURIComponent(ret.data.redirectUri) +
                    "&response_type=code" +
                    "&scope=snsapi_userinfo" +
                    "&state=" +
                    ret.data.state +
                    "#wechat_redirect";
                window.location.href = url; 
                // var tokenNew = GetQueryString("token");
                // sessionStorage.setItem('token', tokenNew);
            } else {
                // alert(ret.data.msg);
                // window.location.href="error.html?code="+ret.code+"&msg="+ret.msg
            }
        } 
    });
}
function GetQueryString(name) {
      var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");  
        var r = window.location.search.substr(1).match(reg);  
        if (r != null) {
            return decodeURIComponent(r[2]);
        }else{
            return ''; 
        }  
  }
export {
    ajax,login
}
